package com.newway.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.newway.common.context.UserInfo;
import com.newway.common.context.UserInfoContext;
import com.newway.common.mapper.UserInfoMapper;
import com.newway.common.result.Result;
import com.newway.entity.Member;
import com.newway.mapper.MemberMapper;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/member")
public class MemberController {

    @Resource
    MemberMapper memberMapper;

    @Resource
    UserInfoMapper userInfoMapper;

    @PostMapping("/joinUs")
    public Result joinUs(@RequestBody Member member){
        QueryWrapper<Member> memberQueryWrapper = new QueryWrapper<>();
        memberQueryWrapper.eq("user_id",UserInfoContext.getUserInfo().getId());
        Member data = memberMapper.selectOne(memberQueryWrapper);
        if(data==null){
            member.setCreateTime(LocalDateTime.now());
            member.setUserId(UserInfoContext.getUserInfo().getId());
            member.setStatus("0");
            memberMapper.insert(member);
            return Result.success();
        }else if("2".equals(data.getStatus())){
            data.setStatus("0");
            data.setInfo(member.getInfo());
            memberMapper.updateById(data);
            return Result.success();
        }
        if("0".equals(data.getStatus())){
            return Result.fail("请等待管理员审核");
        }
        if("1".equals(data.getStatus())){
            return Result.fail("不可重复申请");
        }
        return Result.success();
    }

    //申请退出
    @PostMapping("/outUs")
    public Result outUs(){
        QueryWrapper<Member> memberQueryWrapper = new QueryWrapper<>();
        memberQueryWrapper.eq("user_id",UserInfoContext.getUserInfo().getId());
        Member data = memberMapper.selectOne(memberQueryWrapper);
        if(data!=null){
            memberMapper.deleteById(data.getId());
        }
        return Result.success();
    }

    @GetMapping("/getStatus")
    public Result getStatus(){
        QueryWrapper<Member> memberQueryWrapper = new QueryWrapper<>();
        memberQueryWrapper.eq("user_id", UserInfoContext.getUserInfo().getId());
        Member member = memberMapper.selectOne(memberQueryWrapper);
        return Result.success(member);
    }

    /**
     * 查询入团申请用户
     * @return
     */
    @GetMapping("/joinList")
    public Result getJoinList(){
        QueryWrapper<Member> memberQueryWrapper = new QueryWrapper<>();
        memberQueryWrapper.eq("status", "0");
        List<Member> members = memberMapper.selectList(memberQueryWrapper);

        return Result.success(members);
    }

    @PostMapping("/approval")
    public Result approval(@RequestBody Member member){
        memberMapper.updateById(member);
        return Result.success();
    }
}
